package com.aop;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.annotation.Logging;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.Arrays;

@Aspect
@Component
@Slf4j
public class LoggingAop {

 private Logger logger= LoggerFactory.getLogger(LoggingAop.class);

    @Around( "@annotation(com.annotation.Logging)")
    public Object doAndLog(ProceedingJoinPoint proceedingJoinPoint) {

        // 获取HttpServletRequest
        HttpServletRequest myrequest = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();

        // 获取请求路径
        String requestURI = myrequest.getRequestURI();

        Object[] args=proceedingJoinPoint.getArgs();
       String methodName= proceedingJoinPoint.getSignature().getName();
        Object arg=null;
        if(args.length>0){
            arg= args[0];//入参之物
        }

       //System.out.println("入参{");
        logger.info("---请求开始-----");
        logger.info("请求路径："+requestURI);
        logger.info("方法开始："+methodName);
        logger.info("入参{");
        JSONObject request =null;
        if(args.length>0){
            request=JSONObject.parseObject(JSON.toJSONString(arg));
            for(Object r: request.entrySet()){
                logger.info(r.toString());
            }
        }

        logger.info("}");
        Object result=null;
        try {
            result=  proceedingJoinPoint.proceed();
        } catch (Throwable throwable) {
            throwable.printStackTrace();
        }finally {

           return result;//最终释放
        }
    }

    @AfterReturning(value = "@annotation(com.annotation.Logging)",
    returning ="methodResult" )
    public void returning(JoinPoint joinPoint,Object methodResult){

        logger.info("返回{");
        logger.info(methodResult.toString());
        logger.info("}");
        logger.info("---请求结束-----");
    }


}
